<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="visible"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="上级节点" prop="parentId">
        <el-select
          v-model="formData.parentId"
          placeholder="请选择上级节点"
          style="width: 100%"
        >
          <el-option
            v-for="item in parentOptions"
            :key="item.pkid"
            :label="item.name"
            :value="item.pkid"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="服务地址" prop="url">
        <el-input v-model="formData.url" placeholder="请输入服务地址" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue'

interface TreeItem {
  pkid: string
  name: string
  url: string
  parentId: string
  children?: TreeItem[]
  hasChildren?: boolean
}

interface FormData {
  pkid: string
  name: string
  url: string
  parentId: string | null
}

interface Props {
  visible: boolean
  formData: FormData
  parentOptions: TreeItem[]
  submitLoading?: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'update:formData', value: FormData): void
  (e: 'submit', value: FormData): void
  (e: 'close'): void
}

const props = withDefaults(defineProps<Props>(), {
  submitLoading: false
})

const emit = defineEmits<Emits>()

const formRef = ref()

const dialogTitle = computed(() => (props.formData.pkid ? '编辑' : '新增'))

const formRules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
}

// Watch for visibility changes to sync with parent
watch(() => props.visible, (newVal) => {
  if (!newVal) {
    formRef.value?.resetFields()
  }
})

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    emit('submit', {
      ...props.formData,
      parentId: props.formData.parentId || '-1',
    })
  } catch (error) {
    // Validation failed
  }
}

const handleCancel = () => {
  emit('update:visible', false)
}

const handleClose = () => {
  formRef.value?.resetFields()
  emit('close')
}
</script>

<style scoped lang="scss">
.dialog-footer {
  text-align: right;
}
</style> 